package com.hltx.controller.pay;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alipay.api.AlipayApiException;
import com.hltx.constants.GoodsConstant;
import com.hltx.constants.PayConstant;
import com.hltx.controller.base.BaseController;
import com.hltx.pojo.address.Address;
import com.hltx.pojo.common.Page;
import com.hltx.pojo.goods.GoodsOrder;
import com.hltx.pojo.pay.OrderInfo;
import com.hltx.pojo.pay.PayInfo;
import com.hltx.pojo.pay.PayInfoAlipay;
import com.hltx.pojo.ratioconfigure.RatioConfigure;
import com.hltx.pojo.user.User;
import com.hltx.resolver.DefiniteException;
import com.hltx.service.adress.AddressManager;
import com.hltx.service.goods.GoodsManager;
import com.hltx.service.pay.AlipayPayManager;
import com.hltx.service.pay.PayManager;
import com.hltx.service.user.UserManager;
import com.hltx.util.CustomUtil;
import com.hltx.util.DataUtil;
import com.hltx.util.DateUtil;
import com.hltx.util.ResultInfo;





/**
 * 支付controller
 * 
 * @author shibeilei
 *
 */
@Controller
@RequestMapping("/pay")
public class PayController extends BaseController{

	@Autowired
	private AddressManager addressService;
	
	@Autowired
	private GoodsManager goodsService;
	
	@Autowired
	private UserManager userService;
	
	@Autowired
	private PayManager payService;
	
	@Autowired
	private AlipayPayManager alipayPayService;
	/**
	 * 通过立即购买支付
	 */
	@RequestMapping(value="/buy_now",method = { RequestMethod.POST,RequestMethod.GET})
	public String buyNow(int goodsId,int buyNum,String spec, HttpServletRequest request,HttpSession session,Page page) {
		if(goodsId <= 0 || buyNum <=0){
			throw new DefiniteException("参数不正确！");
		}
		request.setAttribute("goodsId", goodsId);
		request.setAttribute("buyNum", buyNum);
		request.setAttribute("type", "buy_now");
		return "pay/payInfo";
	}
	
	/**
	 * 确认购物车
	 */
	@RequestMapping(value="/confirm_shopCart",method = { RequestMethod.POST,RequestMethod.GET})
	public String index(String goodsId, HttpServletRequest request,Page page,HttpSession session) {
		String id=request.getParameter("addressId");
		page.getParams().put("id",id);
		Address address=addressService.findAddressByID(page);
		request.setAttribute("address", address);
		try{
		if(goodsId == null){
			throw new DefiniteException("参数不正确！");
		}
		StringUtils.split(goodsId, ",");
		}catch(DefiniteException e){
			throw new DefiniteException("参数不正确！");
		}
		request.setAttribute("goodsId", goodsId);
		request.setAttribute("type", "confirm_shopCart");
		return "pay/payInfo";
	}	

	
	@RequestMapping(value = "/getBuyNowGoodsInfo")
	@ResponseBody
	public Map<String,Object> getBuyNowGoodsInfo(int goodsId,String spec,int buyNum,String addressId, HttpServletRequest request,HttpServletResponse response, 
			HttpSession session){
		this.logBefore(logger, "立即购买-查询支付信息");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
			
			User user = (User)session.getAttribute("sessionUser");
			//查询用户基本信息
			user = userService.getUser(user);
			user.setLevel(CustomUtil.strToStr(user.getLevel()));
			//默认收货地址
			List<Address> dAddressList = this.getDefaultAddress(addressId, user);
			resMap.put("dAddressList", dAddressList);
			
			
			//查看商品列表
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("curTime", DateUtil.getTime());
			List<GoodsOrder> goods = goodsService.getGoodsListByGid(goodsId);
			List<GoodsOrder> goodsN = new ArrayList<GoodsOrder>();
			//BigDecimal weight = BigDecimal.ZERO;
			BigDecimal transit = BigDecimal.ZERO;
			spec = StringUtils.equals(spec, "")?"0":spec;
			RatioConfigure ratioConfigure = payService.getRatioConfigure();
			for(GoodsOrder go : goods){
				go.setSpec(spec);
				go.setBuyNum(buyNum);
				//商品是否促销
				params.put("goodsId", go.getId());
				Map<String, Object> goodsSales = goodsService.getGoodsSalesByGId(params);
				if(goodsSales == null){
					go.setIsSales("00");
				}
				BigDecimal bidPrice = go.getBidPrice();
				BigDecimal price = go.getPrice();
				if("01".equals(go.getIsSales())){
					price = go.getRealPrice();
				}
				BigDecimal discount = bidPrice.multiply(DataUtil.getBigDecimal(10)).divide(go.getMarketPrice(), 2 , BigDecimal.ROUND_HALF_DOWN);
				BigDecimal minRatio = ratioConfigure.getMinRatio();
				BigDecimal maxRatio = ratioConfigure.getMaxRatio();
				if(discount.compareTo(maxRatio) <= 0){
					int changePoints =0;
					BigDecimal changePrice = BigDecimal.ZERO;
					if (discount.compareTo(minRatio) == 1) {
						 changePoints = CustomUtil.requiredIntegral(DataUtil.getBigDecimal(price, 2), discount, minRatio);
						 changePrice = price.subtract(DataUtil.getBigDecimal(changePoints, 2));
					}else { 
						 changePoints = price.setScale(0, BigDecimal.ROUND_CEILING).intValue();
					}
					
					go.setChangePoints(changePoints);
					go.setChangePrice(changePrice);
				}
				go.setPrice(price);
				go.setReturnAmount(DataUtil.getBigDecimal(go.getReturnAmount()));
				//获取商品规格 
				Map<String, Object> goodsSpec = null;
				List<Map<String, Object>> goodsSpecPro = null;
				if(StringUtils.equals(go.getIsSelectSpec(), GoodsConstant.SELECT_SPEC_YES)){
					if(StringUtils.isEmpty(go.getSpec())||StringUtils.equals(go.getSpec(), "0")){
						continue;
					}
					params.put("spec", go.getSpec());
					goodsSpec = goodsService.getGoodsSpecBySpec(params);
					if(goodsSpec == null){
						continue;
					}
					goodsSpecPro = goodsService.getGoodsSpecInfoBySpec(params);
					go.setPrice(DataUtil.getBigDecimal(goodsSpec.get("price")));
					go.setBidPrice(DataUtil.getBigDecimal(goodsSpec.get("bidPrice")));
					go.setRealPrice(DataUtil.getBigDecimal(goodsSpec.get("salesPrice")));

				}	
				go.getParams().put("goodsSpec",goodsSpec);
				go.getParams().put("goodsSpecPro",goodsSpecPro);
				goodsN.add(go);
				//weight = weight.add(DataUtil.getBigDecimal(go.getWeight()).multiply(DataUtil.getBigDecimal(go.getBuyNum())));
				transit = transit.add(DataUtil.getBigDecimal(go.getTransitPrice()).multiply(DataUtil.getBigDecimal(go.getBuyNum())));
			}
			//汇总数据，计算运费
			//transit = weight.multiply(DataUtil.getBigDecimal(CourierConstant.WEIGHT_UNIT_PRICE));
			resMap.put("user", user);
			resMap.put("transit", transit);
			resMap.put("goodsList", goodsN);
			resMap.put("ratioConfigure", ratioConfigure);
			if(goodsN.size()>0){
			resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", ""));
			}else{
				resMap.put("result", this.initResult(ResultInfo.ERROR, "ok", "该商品不存在"));	
			}
			
		}catch(Exception e){
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
		}
		this.logAfter(logger);
		return resMap;
	}
	
	@RequestMapping(value = "/getShopCartgInfo", method = { RequestMethod.POST})
	@ResponseBody
	public Map<String,Object> getShopCartgInfo(String goodsId,String addressId, HttpServletRequest request,HttpServletResponse response, 
			HttpSession session){
		this.logBefore(logger, "购物车-查询支付信息");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
			
			User user = (User)session.getAttribute("sessionUser");
			//查询用户基本信息
			user = userService.getUser(user);
			user.setLevel(CustomUtil.strToStr(user.getLevel()));
			//默认收货地址
			List<Address> dAddressList = this.getDefaultAddress(addressId, user);
			resMap.put("dAddressList", dAddressList);
			
			//查看商品列表
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("goodsId", goodsId);
			params.put("userId", user.getId());
			params.put("state", "01");
			params.put("curTime", DateUtil.getTime());
			List<GoodsOrder> goods = goodsService.getGoodsListByShopCart(params);
			List<GoodsOrder> goodsN = new ArrayList<GoodsOrder>();
			//BigDecimal weight = BigDecimal.ZERO;
			BigDecimal transit = BigDecimal.ZERO;
			RatioConfigure ratioConfigure = payService.getRatioConfigure();
			for(GoodsOrder go : goods){
				//商品是否促销
				params.put("goodsId", go.getId());
				Map<String, Object> goodsSales = goodsService.getGoodsSalesByGId(params);
				if(goodsSales == null){
					go.setIsSales("00");
				}
				BigDecimal bidPrice = go.getBidPrice();
				BigDecimal price = go.getPrice();
				if("01".equals(go.getIsSales())){
					price = go.getRealPrice();
				}
				BigDecimal discount = bidPrice.multiply(DataUtil.getBigDecimal(10)).divide(go.getMarketPrice(), 2 , BigDecimal.ROUND_HALF_DOWN);
				BigDecimal minRatio = ratioConfigure.getMinRatio();
				BigDecimal maxRatio = ratioConfigure.getMaxRatio();
				if(discount.compareTo(maxRatio) != 1){
					int changePoints =0;
					BigDecimal changePrice = BigDecimal.ZERO;
					if (discount.compareTo(minRatio) == 1) {
						 changePoints = CustomUtil.requiredIntegral(DataUtil.getBigDecimal(price, 2), discount, minRatio);
						 changePrice = price.subtract(DataUtil.getBigDecimal(changePoints, 2));
					}else { 
						 changePoints = price.setScale(0, BigDecimal.ROUND_CEILING).intValue();
					}
					
					go.setChangePoints(changePoints);
					go.setChangePrice(changePrice);
				}
				go.setPrice(price);
				go.setReturnAmount(DataUtil.getBigDecimal(go.getReturnAmount()));
				//获取商品规格 
				Map<String, Object> goodsSpec = null;
				List<Map<String, Object>> goodsSpecPro = null;
				if(StringUtils.equals(go.getIsSelectSpec(), GoodsConstant.SELECT_SPEC_YES)){
					if(StringUtils.isEmpty(go.getSpec())||StringUtils.equals(go.getSpec(), "0")){
						continue;
					}
					params.put("spec", go.getSpec());
					goodsSpec = goodsService.getGoodsSpecBySpec(params);
					if(goodsSpec == null){
						continue;
					}
					goodsSpecPro = goodsService.getGoodsSpecInfoBySpec(params);
					go.setPrice(DataUtil.getBigDecimal(goodsSpec.get("price")));
					go.setBidPrice(DataUtil.getBigDecimal(goodsSpec.get("bidPrice")));
					go.setRealPrice(DataUtil.getBigDecimal(goodsSpec.get("salesPrice")));

				}	
				go.getParams().put("goodsSpec",goodsSpec);
				go.getParams().put("goodsSpecPro",goodsSpecPro);
				
				goodsN.add(go);
				//weight = weight.add(DataUtil.getBigDecimal(go.getWeight()).multiply(DataUtil.getBigDecimal(go.getBuyNum())));
				transit = transit.add(DataUtil.getBigDecimal(go.getTransitPrice()).multiply(DataUtil.getBigDecimal(go.getBuyNum())));

			}
			//汇总数据，计算运费
			//transit = weight.multiply(DataUtil.getBigDecimal(CourierConstant.WEIGHT_UNIT_PRICE));
			resMap.put("user", user);
			resMap.put("transit", transit);
			resMap.put("goodsList", goodsN);
			resMap.put("ratioConfigure", ratioConfigure);
			if(goodsN.size() > 0){
			resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", ""));
			}else{
				resMap.put("result", this.initResult(ResultInfo.ERROR, "ok", "购物车空了！"));	
			}
		}catch(Exception e){
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
		}
		this.logAfter(logger);
		return resMap;
	}	
	/**
	 * 查询默认收货地址
	 * @param addressId
	 * @param user
	 * @return
	 */
	private List<Address> getDefaultAddress(String addressId, User user){
		List<Address> dAddressList;
		if(StringUtils.isNotEmpty(addressId)){
			Page p = new Page();
			p.getParams().put("id", addressId);
			Address address = addressService.findAddressByID(p);
			dAddressList = new ArrayList<Address>();
			dAddressList.add(address);
		}else{
		 dAddressList = addressService.findDefaultAddressByUserId(user.getId());
		}
		return dAddressList;
	}
	
	/**
	 * 购物车打开个人地址页面
	 */
	@RequestMapping(value="/confirm_address", method = { RequestMethod.POST})
	public String confirmAddress(String goodsId, HttpServletRequest request) {
		try{
			if(goodsId == null){
				throw new DefiniteException("参数不正确！");
			}
			StringUtils.split(goodsId, ",");
			}catch(DefiniteException e){
				throw new DefiniteException("参数不正确！");
			}
			request.setAttribute("goodsId", goodsId);
			request.setAttribute("type", "confirm_shopCart");
		return "pay/address";
	}
	
	/**
	 * 立即购买打开个人地址页面
	 */
	@RequestMapping(value="/buy_now_address", method = { RequestMethod.POST})
	public String buyNowAddress(int goodsId,int buyNum,String spec, HttpServletRequest request) {
		if(goodsId <= 0 || buyNum <=0){
			throw new DefiniteException("参数不正确！");
		}
		request.setAttribute("goodsId", goodsId);
		request.setAttribute("buyNum", buyNum);
		request.setAttribute("type", "buy_now");
		return "pay/address";
	}	
	
	public String payResult(String code){
		if(StringUtils.isEmpty(code)){
			throw new DefiniteException("参数不正确！");
		}
		
		if(!StringUtils.isNumeric(code)){
			throw new DefiniteException("参数不正确！");
		}
		
		return "";
	}
	@RequestMapping(value="/payOneResult", method = { RequestMethod.GET})
	public String payOneResult(String code, HttpServletRequest request){
		if(StringUtils.isEmpty(code) || StringUtils.length(code)<12){
			throw new DefiniteException("参数不正确！");
		}
		
		if(!StringUtils.isNumeric(code)){
			throw new DefiniteException("参数不正确！");
		}
		
		int payId = CustomUtil.getId(code, 4, 7);
		
		
		//查询支付信息
		PayInfo pi = payService.getPayStateById(payId);
		if(pi == null){
			throw new DefiniteException("支付信息不存在！");
		}
		
		if(StringUtils.equals(pi.getState(), PayConstant.PAY_NO)){
			return "pay/payFailed";
		}
		
		//查询订单信息
		List<OrderInfo> oiList = payService.getOrderInfoByPayId(payId);
		//查询订单商品信息
		for(int i=0; i<oiList.size(); i++){
			OrderInfo oi = oiList.get(i);
			List<GoodsOrder> goList = payService.getGoodsOrderByOrderId(oi.getId());
			int num = 0;
			if(goList!=null && goList.size() >0){
				num = goList.size();
			}
			request.setAttribute("num", num);
			request.setAttribute("oi", oi);
			request.setAttribute("goList", goList);
		}
		
		return "pay/paySuccess";
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/aliPayReturn")
	public String aliPayReturn(HttpServletRequest request,
			HttpServletResponse response){
		 Map<String, String> map = new HashMap<String, String>();
		 try {
		 Map<String, String[]> params = request.getParameterMap();
         for (Entry<String, String[]> entry : params.entrySet()) {
             if (entry.getValue() != null && entry.getValue().length == 1) {
                 map.put(entry.getKey(), entry.getValue()[0]);
             }
         }
         PayInfoAlipay result = alipayPayService.getReturnResult(map);
         System.out.println(result.getOutTradeNo());
         return "redirect:/pay/payOneResult?code="+result.getOutTradeNo();
		 }catch(AlipayApiException e){
			 throw new DefiniteException(e.getMessage()); 
		 }
		 
		 
	}

}
